package com.solotiger.okex.service.impl;

import com.solotiger.okex.common.util.TokenGenerator;
import com.solotiger.okex.dao.UserTokenDao;
import com.solotiger.okex.domain.OkexUserToken;
import com.solotiger.okex.service.OkexUserTokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;

/**
 * 用户登录TOKEN
 * Author: Lin.Qiang
 * Date:2018/6/1 0001
 */
@Service
public class OkexUserTokenServiceImpl implements OkexUserTokenService {

    //过期时间30天
    private final static int EXPIRE = 30;

    @Autowired
    private UserTokenDao userTokenDao;

    @Override
    public OkexUserToken findByToken(String token) {
        return userTokenDao.findByToken(token);
    }

    @Override
    public OkexUserToken createToken(Integer userId) {
        //生成一个token
        String token = TokenGenerator.generateValue();
        String refreshToken = TokenGenerator.generateValue();

        //当前时间
        Date now = new Date();
        Calendar cd = Calendar.getInstance();
        cd.setTime(now);
        cd.add(Calendar.DATE, EXPIRE);//增加EXPIRE天
        //过期时间
        Date expireTime = cd.getTime();
//        SimpleDateFormat sp = new SimpleDateFormat("yyyy-MM-dd HH:ss:mm");
//        System.out.println(sp.format(now));
//
//        System.out.println(sp.format(expireTime));

        //判断是否生成过token
        OkexUserToken tokenEntity = userTokenDao.findByUserId(userId);
        if(tokenEntity == null){
            tokenEntity = new OkexUserToken();
            tokenEntity.setUserId(userId);
            tokenEntity.setToken(token);
            tokenEntity.setRefreshToken(refreshToken);
            tokenEntity.setUpdateTime(now);
            tokenEntity.setExpireTime(expireTime);
            //保存token
            userTokenDao.save(tokenEntity);
        }else{
//			tokenEntity.setToken(token);//更新token, 踢掉之前token
            tokenEntity.setToken(token);
            tokenEntity.setRefreshToken(refreshToken);
            tokenEntity.setUpdateTime(now);
            tokenEntity.setExpireTime(expireTime);
            //更新token
            userTokenDao.update(tokenEntity);
        }
        return tokenEntity;
    }

    @Override
    public void logout(Integer userId) {
        //生成一个token
        String token = TokenGenerator.generateValue();
        String refreshToken = TokenGenerator.generateValue();
        OkexUserToken tokenEntity = new OkexUserToken();
        tokenEntity.setUserId(userId);
        //修改Token
        tokenEntity.setToken(token);
        tokenEntity.setRefreshToken(refreshToken);
        tokenEntity.setUpdateTime(new Date());
        userTokenDao.update(tokenEntity);
    }
}
